package order

import (
	"api/pb/order"
	"context"
	"errors"
	"fmt"
	"strconv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetOrderListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderListLogic {
	return &GetOrderListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetOrderListLogic) GetOrderList(req *types.OrderListRequest) (resp *types.OrderListResponse, err error) {
	userIdStr := l.ctx.Value("user_id").(string)
	fmt.Println(userIdStr)
	if userIdStr == "" {
		return nil, fmt.Errorf("user_id not found")
	}

	userId, err := strconv.ParseInt(userIdStr, 10, 64)
	if userId == 0 {
		return nil, errors.New("user_id not found")
	}

	orderList, err := l.svcCtx.OrderRpc.GetOrderList(l.ctx, &order.ListRequest{UserId: userId, Page: req.Page, PageSize: req.PerPage})
	if err != nil {
		return nil, err
	}

	resp = &types.OrderListResponse{
		Total: orderList.Total,
		Pages: orderList.Pages,
		Data:  make([]types.Order, 0),
	}
	for _, o := range orderList.Orders {
		var goods []types.OrderGood
		for _, g := range o.Goods {
			goods = append(goods, types.OrderGood{
				Id:    g.GoodId,
				Name:  g.GoodName,
				Price: g.GoodPrice,
				Count: g.GoodCount,
			})
		}

		resp.Data = append(resp.Data, types.Order{
			UserId:      o.UserId,
			OrderId:     o.OrderId,
			OrderStatus: o.OrderStatus,
			OrderTotal:  o.OrderTotal,
			CreateTime:  o.CreateTime,
			UpdateTime:  o.UpdateTime,
			DeleteTime:  o.DeleteTime,
			Goods:       goods,
		})
	}
	return resp, nil
}
